package br.com.werp.regras.geral.util;

import br.com.werp.regras.geral.FabricaSubSistema;
import br.com.werp.regras.geral.Relatorio;

import java.io.InputStream;

import java.net.URL;


/**
 * @author Sobreira
 * Criado em 04/01/2005
 *
 */
public class CarregadorRecurso {
    public static URL carregarRelatorioURL(String arquivo, Object subSistema)
        throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        String pacote = subSistema.getClass().getPackage().getName();
        String ancora = pacote + ".visao.relatorios.Ancora";

        return Class.forName(ancora).newInstance().getClass().getResource(arquivo +
            ".jasper");
    }

    public static InputStream carregarRelatorioStream(String arquivo,
        Object subSistema, String tipo)
        throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        String pacote = subSistema.getClass().getPackage().getName();
        String ancora = pacote + ".visao.relatorios.Ancora";

        if (Relatorio.TIPO_XLS.equals(tipo)) {
            try {
                InputStream stream = Class.forName(ancora).newInstance()
                                          .getClass().getResourceAsStream(arquivo +
                        "Xls.jasper");

                if (stream == null) {
                    stream = Class.forName(ancora).newInstance().getClass()
                                  .getResourceAsStream(arquivo + ".jasper");
                }

                return stream;
            } catch (Exception e) {
                return Class.forName(ancora).newInstance().getClass()
                            .getResourceAsStream(arquivo + ".jasper");
            }
        }

        return Class.forName(ancora).newInstance().getClass()
                    .getResourceAsStream(arquivo + ".jasper");
    }

    public static void main(String[] args)
        throws InstantiationException, IllegalAccessException, 
            ClassNotFoundException {
        System.out.println(carregarRelatorioURL("Graficos",
                FabricaSubSistema.getAuditoria()));
    }
}
